package com.hd.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hd.auth.AuthService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器类, 可以在这里作用户登陆鉴权. 通过 WebMvcConfig 类 注册到 SpringMvc 中.
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	AuthService authService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String headToken = request.getHeader("Authorization");
		String uri = request.getRequestURI();

		// 不进行拦截的请求
		if (uri.contains("/auth/refreshToken") || uri.contains("/user/register") || uri.contains("/user/sendSMS")
				|| uri.contains("/user/resetPwd") || uri.contains("/user/other") || uri.contains("/user/login")
				|| uri.contains("/user/oAuthLogin") || uri.contains("/user/nextStep") || uri.contains("/wechat")
				|| uri.contains("/v2/api-docs") || uri.contains("swagger") || uri.contains("error")
				|| uri.contains("swg") || uri.contains("configuration")) {
			return super.preHandle(request, response, handler);
		}

		if (StringUtils.isEmpty(headToken)) {
			throw new Exception("你还没有登录，请前往登录");
		}
		if (headToken.length() < 8) {
			throw new Exception("token错误");
		}

		/*
		 * String token = headToken.substring("Bearer ".length()); Account
		 * account=accountService.getAccountByToken(token); if(account==null){ throw new
		 * Exception("权限不足"); } accountId = account.getId();
		 * 
		 * if (new Date().after(account.getExpireAt())) { throw new
		 * Exception("认证信息过期，请重新登录！ "); } //认证成功将用户信息放进request
		 * request.setAttribute("accountId", accountId); request.setAttribute("account",
		 * account);
		 */

		return super.preHandle(request, response, handler);
	}

}
